<template>
  <div class="chat-container">
    <div class="chat-header">
      <h2>AI 聊天助手 Beta</h2>
    </div>
    <div class="chat-messages" ref="messagesContainer">
      <div v-for="(message, index) in messages" :key="index" :class="['message', message.sender === 'user' ? 'user-message' : 'ai-message']">
        <div class="message-content">
            {{ message.content }}
            <img v-if="message.imageUrl" :src="message.imageUrl" class="message-image" />
          </div>
        <div class="message-time">{{ formatTime(message.timestamp) }}</div>
      </div>
      <div v-if="isLoading" class="loading-indicator">
        <div class="dot-pulse">
          <span></span>
          <span></span>
          <span></span>
        </div>
      </div>
    </div>
    <div class="chat-input-area">
      <input
        v-model="userInput"
        @keyup.enter="sendMessage"
        placeholder="输入您的问题..."
        class="message-input"
      />
      <input type="file" id="file-upload" accept="image/*" @change="handleFileChange" class="file-input" />
      <label for="file-upload" class="upload-button">📷 上传图片</label>
      <button @click="sendMessage" class="send-button">发送</button>
        <div v-if="imagePreviewUrl" class="image-preview-container">
          <img :src="imagePreviewUrl" class="image-preview" />
          <button @click="clearImagePreview" class="clear-preview">×</button>
        </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  data() {
    return {
      messages: [],
      userInput: '',
      isLoading: false,
      selectedFile: null,
      imagePreviewUrl: null
    };
  },
  methods: {
      /**
       * 清除图片预览和选中状态
       */
    clearImagePreview() {
      this.selectedFile = null;
      this.imagePreviewUrl = null;
      document.getElementById('file-upload').value = '';
    },
    /**
     * 处理文件选择事件，读取图片并显示预览
     * @param {Event} e - 文件选择事件
     */
    handleFileChange(e) {
      this.selectedFile = e.target.files[0];
      if (this.selectedFile) {
        const reader = new FileReader();
        reader.onload = (e) => {
          this.imagePreviewUrl = e.target.result;
        };
        reader.readAsDataURL(this.selectedFile);
      } else {
        this.imagePreviewUrl = null;
      }
    },
    /**
     * 发送消息到AI聊天接口
     * 根据是否有选中文件选择不同的API端点
     * - 有文件: 使用POST /aiChat/media接口上传图片和文本
     * - 无文件: 使用GET /aiChat/ai接口发送纯文本
     */
    sendMessage() {
    if (!this.userInput.trim()) {      this.$message.warning('请您输入想要询问的问题');      return;    } 

    // 添加用户消息
    this.messages.push({
      sender: 'user',
      content: this.userInput,
      timestamp: new Date(),
      imageUrl: this.imagePreviewUrl || null
    });

    const userMessage = this.userInput.trim();
    this.userInput = '';
    this.isLoading = true;
    this.scrollToBottom();

    if (this.selectedFile) {
      // 有图片，使用新接口
      const formData = new FormData();
      formData.append('file', this.selectedFile);
      formData.append('text', userMessage);

      // 使用axios上传文件和文本
      axios.post('http://localhost:8080/aiChat/media', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      .then(response => {
        this.selectedFile = null; // 清除选中的文件
        this.imagePreviewUrl = null; // 清除图片预览
        document.getElementById('file-upload').value = ''; // 重置文件输入
        const aiResponse = response.data;

        // 添加AI回复
        this.messages.push({
          sender: 'ai',
          content: aiResponse,
          timestamp: new Date()
        });
      })
      .catch(error => {
        this.messages.push({
          sender: 'ai',
          content: '抱歉，无法连接到服务器，请稍后再试。',
          timestamp: new Date()
        });
      })
      .finally(() => {
        this.isLoading = false;
        this.scrollToBottom();
      });
    } else {
      // 无图片，使用老接口
      // 使用axios发送纯文本请求
      axios.get('http://localhost:8080/aiChat/ai', {
        params: {
          userInput: userMessage
        }
      })
      .then(response => {
        const aiResponse = response.data;

        // 添加AI回复
        this.messages.push({
          sender: 'ai',
          content: aiResponse,
          timestamp: new Date()
        });
      })
      .catch(error => {
        this.messages.push({
          sender: 'ai',
          content: '抱歉，无法连接到服务器，请稍后再试。',
          timestamp: new Date()
        });
      })
      .finally(() => {
        this.isLoading = false;
        this.scrollToBottom();
      });
    }
  },
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer;
        container.scrollTop = container.scrollHeight;
      });
    },
    formatTime(date) {
      return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
    }
  }
};
</script>

<style scoped>
.chat-container {
  max-width: 1200px;
  margin: 0 auto;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
  overflow: hidden;
}

.chat-header {
  background: linear-gradient(135deg, #4a6cf7, #1e40af);
  color: white;
  padding: 15px 20px;
  text-align: center;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  position: relative;
  overflow: hidden;
}

.chat-header h2 {
  font-size: 1.5rem;
  margin: 0;
}

.chat-messages {
  flex: 1;
  padding: 30px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message {
  max-width: 75%;
  padding: 15px 20px;
  border-radius: 20px;
  position: relative;
  animation: slideIn 0.3s ease forwards;
  transform-origin: center bottom;
  opacity: 0;
  transform: translateY(10px);
}

.user-message {
  align-self: flex-end;
  background: linear-gradient(135deg, #4a6cf7, #3a86ff);
  color: white;
  box-shadow: 0 4px 12px rgba(74, 108, 247, 0.25);
}

.ai-message {
  align-self: flex-start;
  background-color: white;
  color: #333;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.message-time {
  margin-top: 8px;
  font-size: 12px;
  color: #9ca3af;
  text-align: right;
}

.user-message .message-time {
  right: 20px;
}

.ai-message .message-time {
  text-align: left;
}

.chat-input-area {
  display: flex;
  padding: 20px;
  gap: 15px;
  background-color: white;
  border-top: 1px solid #eee;
}

.message-input {
  flex: 1;
  padding: 15px 20px;
  border: 1px solid #e5e7eb;
  border-radius: 30px;
  font-size: 16px;
  outline: none;
  transition: all 0.3s ease;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.03);
}

.message-input:focus {
  border-color: #4a6cf7;
  box-shadow: 0 0 0 3px rgba(74, 108, 247, 0.1);
}

.message-input:focus {
  border-color: #3498db;
}

.send-button {
  padding: 15px 30px;
  background: linear-gradient(135deg, #4a6cf7, #3a86ff);
  color: white;
  border: none;
  border-radius: 30px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(74, 108, 247, 0.25);
}

.send-button:hover {
  background: linear-gradient(135deg, #3a5ce7, #2a75e6);
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(74, 108, 247, 0.3);
}

.send-button:active {
  transform: translateY(0);
  box-shadow: 0 4px 10px rgba(74, 108, 247, 0.2);
}

.file-input {
  display: none;
}

.upload-button {
  padding: 15px 30px;
  border-radius: 30px;
  background-color: #e5e7eb;
  color: #333;
  border: none;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.upload-button:hover {
  background-color: #d1d5db;
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

.upload-button:active {
  background-color: #b5b9c2;
  transform: translateY(0);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.message-image {
  max-width: 200px;
  max-height: 200px;
  border-radius: 8px;
  margin-top: 8px;
}

.image-preview-container {
  position: relative;
  margin-top: 10px;
}

.image-preview {
  max-width: 150px;
  max-height: 150px;
  border-radius: 8px;
}

.clear-preview {
  position: absolute;
  top: -8px;
  right: -8px;
  background-color: #ff4d4f;
  color: white;
  border: none;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 16px;
  padding: 0;
}

.send-button:hover {
  background-color: #2980b9;
}

.send-button:active {
  transform: scale(0.98);
}

.loading-indicator {
  align-self: flex-start;
  padding: 15px 20px;
}

.dot-pulse {
  display: flex;
  gap: 6px;
}

.dot-pulse span {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #4a6cf7;
  animation: dotPulse 1.5s infinite ease-in-out;
}

.dot-pulse span:nth-child(2) {
  animation-delay: 0.2s;
}

.dot-pulse span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes dotPulse {
  0%, 100% {
    opacity: 0.4;
    transform: scale(0.8);
  }
  50% {
    opacity: 1;
    transform: scale(1);
  }
}

.dot-pulse {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #3498db;
  position: relative;
  animation: dotPulse 1.5s infinite;
}

@keyframes dotPulse {
  0% { transform: scale(0); opacity: 0; }
  50% { opacity: 1; }
  100% { transform: scale(1); opacity: 0; }
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .message {
    max-width: 85%;
  }
}
</style>